package com.itheima.health.controller;

import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.Result;
import com.itheima.health.exception.BusinessRuntimeException;
import com.itheima.health.pojo.OrderSetting;
import com.itheima.health.service.OrderSettingService;
import com.itheima.health.vo.OrderSettingVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author ：Eason
 * @date ：Created in 2022年06月10日
 * @description ：
 * @version: 1.0
 */
@RestController
@RequestMapping("/ordersetting")
@Slf4j
public class OrderSettingController {

    @Autowired
    private OrderSettingService orderSettingService;



    @PostMapping("/upload")
    public Result upload(@RequestParam("excelFile") MultipartFile multipartFile){
        //获取文件名,判断是否文件名为空
        String filename = multipartFile.getOriginalFilename();
        if (StringUtils.isEmpty(filename)){
            return new Result(false,"缺少文件名字");
        }
        //抽取sxcel数据
        Workbook workbook=null;

        try(InputStream in = multipartFile.getInputStream();){
            if (filename.endsWith(".xls")){
                workbook= new HSSFWorkbook(in);
            }else if (filename.endsWith(".xlsx")){
                workbook=new XSSFWorkbook(in);
            }else {
                return new Result(false,"文件格式不对额");
            }
        }catch (IOException e){
            return new Result(false,"文件上传失败");
        }
        //遍历取出数据
        List<OrderSetting> orderSettings=new ArrayList<>();
        for (Sheet sheet : workbook) {
            //从第1行去取数据
            for (int i =1;i <=sheet.getLastRowNum();i++){
                //获取行数据
                Row row = sheet.getRow(i);
                //解析行数据
                OrderSetting orderSetting = parseOrderSetting(row);
                orderSettings.add(orderSetting);
            }
        }
        log.info("预约设置的上传文件解析成功,结果是:{}"+orderSettings);
        //2 service调用数据入库
        for (OrderSetting orderSetting : orderSettings) {
            orderSettingService.editNumberByDate(orderSetting);
        }
        return new Result(true,MessageConst.IMPORT_ORDERSETTING_SUCCESS);
    }

    private OrderSetting parseOrderSetting(Row row) {
        Date date = null;
        Integer number = null;
        try {
            //获取日期
            if(null != row.getCell(0) ){
                //如果单元格没有数据，则getDateCellValue返回null
                date = row.getCell(0).getDateCellValue();
            }
            //获取最大预约数量
            if(null != row.getCell(1)){
                //如果单元格没有数据，则getNumericCellValue返回0
                double numberValue = row.getCell(1).getNumericCellValue();
                //将double型转为int型
                number =  Double.valueOf(numberValue).intValue();
            }
        }catch (IllegalStateException|NumberFormatException e){
            log.error("",e);
            throw new BusinessRuntimeException(String.format("数据格式错误,%s 第%d行",row.getSheet().getSheetName(),row.getRowNum()+1));
        }
        // 判断是否缺少数据
        if(null == date || null == number){
            throw new BusinessRuntimeException(String.format("缺少必填数据,%s 第%d行",row.getSheet().getSheetName(),row.getRowNum()+1));
        }
        return new OrderSetting(date,number);
    }


    //查询日历展示
    @GetMapping("/getOrderSettingByMonth")
    public Result getOrderSettingByMonth(Integer year, Integer month){
        List<OrderSettingVo> orderSettingVoList= orderSettingService.getOrderByMonth(year,month);
        return new Result(true, MessageConst.ACTION_SUCCESS,orderSettingVoList);
    }

    /**
     * 根据日期变更最大可预约数
     * @param orderSetting
     * @return
     */
    @PostMapping("/editNumberByDate")
    public Result editNumberByDate(@RequestBody OrderSetting orderSetting){
        orderSettingService.editNumberByDate(orderSetting);
        return new Result(true,MessageConst.ORDERSETTING_SUCCESS);
    }
}